package com.retailshop.shopuser.WapUserController;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.retailshop.shopuser.common.*;
import com.retailshop.shopuser.entity.*;
import com.retailshop.shopuser.service.UserBankService;
import com.retailshop.shopuser.service.UserNoService;
import com.retailshop.shopuser.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@CrossOrigin
@Controller
@RequestMapping("/wap")
public class WapUserController {

    @Autowired
    UserService userService;

    @Autowired
    UserNoService userNoService;

    @Autowired
    TokenUtils tokenUtils;

    @Autowired
    SMSConfig smsConfig;

    @Autowired
    UserBankService userBankService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    FinaceConfig finace;

    private static final String KEY = "xlsphone2019";
    Logger logger = LoggerFactory.getLogger(WapUserController.class);

    /**
     * 查询手机号
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getUserInfoByPhone", method = RequestMethod.POST)
    public Response getUserInfoByPhone(HttpServletRequest request) {
        List<User> usersList = null;
        String phone = request.getParameter("phone");
        //获取缓存数据
        Object object = redisTemplate.opsForValue().get("phone" + phone);
        if (object != null) {
            usersList = (List<User>) object;

        } else {
            if (OtherConstants.RegexpPhone(phone)) {
                User user = new User();
                user.setPhone(phone);
                usersList = userService.selectUserByPhone(user);
            }
        }

        if (usersList == null || usersList.size() == 0) {
            return new Response(MessageConstants.MSG_PHONE_NOEXIT, null, "", request);
        }
        return new Response(MessageConstants.MSG_PHONE_EXSIT, usersList.size(), "", request);
    }


    /**
     * 手机号
     *
     * @param phone
     * @param request
     * @return
     */
    //发送验证码
    @ResponseBody
    @RequestMapping("/sendCodeByPhone")
    public Response sendCodeByPhone(String phone, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        try {
            if (OtherConstants.RegexpPhone(phone)) {
                map = userNoService.sendCodeByPhone(phone, request);
                return new Response(MessageConstants.MSG_SUCCESS, map, 0, "", request);
            } else {
                return new Response(MessageConstants.MSG_VERIFY_PHONE_ERROR, null, 0, "手机号错误！", request);
            }

        } catch (Exception e) {
            return new Response(MessageConstants.MSG_VERIFY_SEND_FAILED, null, 0, "运行异常！", request);
        }
    }

    /**
     * 手机号注册
     *
     * @param map     手机号，短信验证码
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/userRegisterByPhone", method = RequestMethod.POST)
    public Response userRegisterByPhone(@RequestParam Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) {
        UserNo userNo = null;
        JSONObject jsonObject = new JSONObject();
        try {
            userNo = userNoService.userRegister(map, request);

        } catch (Exception e) {
            e.printStackTrace();
            return new Response(MessageConstants.MSG_REGISTER_FAILED, null, 0, "运行异常！", request);
        }

        if (userNo != null) {
            String token = tokenUtils.getToken(userNo);
            jsonObject.put("token", token);
            jsonObject.put("userNo", userNo);
            //注册成功后，返回代金券
            return new Response(MessageConstants.MSG_SUCCESS, jsonObject, 0, "注册成功！", request);
        } else {
            return new Response(MessageConstants.MSG_REGISTER_FAILED, null, 0, "添加注册数据失败！", request);
        }

    }

    /**
     * 用户手机号登录
     *
     * @param map
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/userLoginByPhone")
    public Response userLoginByPhone(@RequestParam Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) {
        UserNo userNo = null;
        JSONObject jsonObject = new JSONObject();
        try {

            userNo = userNoService.userLoginByPhone(map, request);
            if (userNo != null) {
                String token = tokenUtils.getToken(userNo);
                jsonObject.put("token", token);
                jsonObject.put("userNo", userNo);
                Cookie cookie = new Cookie("loginSign", "1");//cookie保存一个手机号登录状态
                response.addCookie(cookie);
                return new Response(MessageConstants.MSG_VALID_LOGIN, jsonObject, 0, "登录成功！", request);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new Response(MessageConstants.MSG_INVALID_LOGIN, null, 0, "运行异常！", request);
        }

        return new Response(MessageConstants.MSG_INVALID_LOGIN, null, 0, "验证码为空！", request);
    }

    /**
     * 用户账号登录
     *
     * @param map
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/userLoginByUserNo", method = RequestMethod.POST)
    public Response userLoginByUserNo(@RequestParam Map<String, Object> map, HttpServletRequest request) {
        UserNo userNo = null;
        JSONObject jsonObject = new JSONObject();
        try {
            userNo = userNoService.userLoginByPwd(map, request);
            if (userNo != null) {
                String token = tokenUtils.getToken(userNo);
                jsonObject.put("token", token);
                jsonObject.put("userNo", userNo);
                return new Response(MessageConstants.MSG_SUCCESS, jsonObject, 0, "", request);
            } else {
                return new Response(MessageConstants.MSG_INVALID_LOGIN, null, 0, "", request);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new Response(MessageConstants.MSG_INVALID_LOGIN, null, 0, "运行异常！", request);
        }
    }


    /**
     * 用户设置密码
     *
     * @param
     * @param request
     * @return
     */
    @UserLoginToken
    @ResponseBody
    @RequestMapping(value = "/updateUserNoLoginPwd", method = RequestMethod.POST)
    public Response updateUserNoLoginPwd(HttpServletRequest request) {
        try {
            boolean flag = userNoService.updateUserNoLoginPwd(request);
            if (flag) {
                return new Response(MessageConstants.MSG_SUCCESS, true, 0, "", request);
            } else {
                return new Response(MessageConstants.MSG_ILLEGAL_ARGUMENT, true, 0, "", request);
            }

        } catch (Exception e) {
            return new Response(MessageConstants.MSG_SYS_ERROR, false, 0, "", request);
        }
    }


    /**
     * 获取用户信息
     *
     * @param userNoId
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/getUserNoIdInfoByUserNoId")
    public Response getUserNoIdInfoByUserNoId(@RequestParam String userNoId, HttpServletRequest request) {
        int userNoIds = 0;
        UserNo userNo = null;
        if (userNoId != null && userNoId != "") {
            userNoIds = Integer.parseInt(userNoId);
            if (userNoIds != 0) {
                userNo = userNoService.selectByPrimaryKey(userNoIds);
            }

        }

        if (userNo != null) {
            return new Response(MessageConstants.MSG_SUCCESS, userNo, 0, "", request);
        } else {
            return new Response(MessageConstants.MSG_USER_INEXISTENCE, null, 0, "", request);
        }

    }

    /**
     * 根据用户获取用户信息
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/getUserNoInfo")
    public Response getUserNoInfo(HttpServletRequest request) {
        String userNoId = request.getParameter("userNoId");
        int userNoIds = 0;
        if (userNoId != null && userNoId != "") {
            userNoIds = Integer.parseInt(userNoId);
            UserNo userNo = userNoService.selectByPrimaryKey(userNoIds);
            if (userNo != null) {
                return new Response(MessageConstants.MSG_SUCCESS, userNo, 0, "", request);
            } else {
                return new Response(MessageConstants.MSG_REQUEST_STATE, null, 0, "", request);
            }
        } else {
            return new Response(MessageConstants.MSG_USER_INEXISTENCE, null, 0, "", request);
        }


    }

    /**
     * 修改银行接口
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateBankInfo")
    public Response updateBankInfo(HttpServletRequest request) {
        String ucIds = request.getParameter("ucId");
        String bankName = request.getParameter("bankName");
        String bankCardNo = request.getParameter("bankCardNo");
        String userNoIds = request.getParameter("userNoId");
        int userNoId = 0;
        int userId = 0;
        if (userNoIds != null && userNoIds != "") {
            if (StringUtil.isNumeric(userNoIds)) {
                userNoId = Integer.parseInt(userNoIds);
                UserNo userNo = userNoService.selectByPrimaryKey(userNoId);
                if (userNo != null) {
                    userId = userNo.getUserId();
                }
            }
        }

        int ucId = 0;
        if (ucIds != null && ucIds != "" && StringUtil.isNumeric(ucIds)) {//修改
            ucId = Integer.parseInt(ucIds);

            UserBank userBank = new UserBank();
            userBank.setBankCardNo(bankCardNo);
            userBank.setBankName(bankName);
            userBank.setUserId(userId);
            userBank.setUcId(ucId);
            int rows = userBankService.updateByPrimaryKeySelective(userBank);
            if (rows > 0) {
                return new Response(MessageConstants.MSG_SUCCESS, rows, 0, "更新成功！", request);
            } else {
                return new Response(MessageConstants.MSG_SYS_ERROR, null, 0, "更新失败！", request);
            }

        } else {//为空则添加

            UserBank userBank = new UserBank();
            userBank.setBankCardNo(bankCardNo);
            userBank.setBankName(bankName);
            userBank.setUserId(userId);
            int row = userBankService.insertSelective(userBank);
            if (row > 0) {
                return new Response(MessageConstants.MSG_SUCCESS, row, 0, "新增成功！", request);
            } else {
                return new Response(MessageConstants.MSG_SUCCESS, null, 0, "新增失败！", request);
            }

        }


    }


    /**
     * 店主申请店铺
     *
     * @param
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/applyStore", method = RequestMethod.POST)
    public Response applyStore(HttpServletRequest request) {


        int userTotal = 0;
        int userNoId = 0;
        int sharerTotal = 0;
        String userNoIds = request.getParameter("userNoId");
        try {
            if (StringUtil.isNumeric(userNoIds)) {
                userNoId = Integer.parseInt(userNoIds);
            }

//                userTotal = userNoService.statsShareUserNo(userNoId);
            UserNo userNo = userNoService.selectByPrimaryKey(userNoId);
            if (userNo != null) {
                sharerTotal = userNo.getSharerTotal();
            }
            sharerTotal = 200;
            System.out.println("ustoal====" + userTotal);
            if (sharerTotal < 200) {
                return new Response(MessageConstants.MSG_FAILED, null, 0, "您用户量没达到200，还不能申请店铺！", request);
            }

            boolean flag = userNoService.applyStore(request);
            if (flag) {
                return new Response(MessageConstants.MSG_SUCCESS, flag, 0, "申请成功！", request);
            } else {
                return new Response(MessageConstants.MSG_FAILED, flag, 0, "申请失败！", request);
            }
        } catch (Exception e) {
            e.printStackTrace();
            new Response(MessageConstants.MSG_SYS_ERROR, null, "", request);
        }


        return new Response(MessageConstants.MSG_ILLEGAL_ARGUMENT, null, "", request);


    }


    /**
     * 修改个人资料
     */
    @ResponseBody
    @RequestMapping("/getUserInfo")
    public Response getUserInfo(HttpServletRequest request) {
        String userNoIds = request.getParameter("userNoId");
        int userNoId = 0;
        if (userNoIds != null && userNoIds != "") {
            userNoId = Integer.parseInt(userNoIds);
        }

        UserInfo userInfo = userNoService.getUserInfo(userNoId);
        if (userInfo != null) {
            Date date = new Date();
            date = userInfo.getBirthday();
            if (date == null) {
                date = new Date(System.currentTimeMillis());
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String s = sdf.format(date);

            userInfo.setFormatBirthday(s);

            return new Response(MessageConstants.MSG_SUCCESS, userInfo, 0, "", request);
        } else {
            return new Response(MessageConstants.MSG_ITEM_NOT_EXIST, userInfo, 0, "", request);
        }

    }


    /**
     * 修改用户资料
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateUserInfo")
    public Response updateUserInfo(HttpServletRequest request) {
        //修改昵称
        String nick = request.getParameter("nick");
        String userNoIds = request.getParameter("userNoId");
        String gender = request.getParameter("gender");
        String birthday = request.getParameter("birthday");
        String wechat = request.getParameter("wechat");

        String phone = request.getParameter("phone");
        String code = request.getParameter("code");
        String codeTime = request.getParameter("codeTime");
        String requestHash = request.getParameter("hash");
        int userId = 0;
        int userNoId = 0;
        if (userNoIds != null && userNoIds != "") {
            userNoId = Integer.parseInt(userNoIds);
        }

        UserNo userNo1 = userNoService.selectByPrimaryKey(userNoId);
        if (userNo1 != null) {
            userId = userNo1.getUserId();
        }

        if (nick != null && nick != "") {
            UserNo userNo = new UserNo();
            userNo.setNick(nick);
            userNo.setId(userNoId);
            int row = userNoService.updateByPrimaryKeySelective(userNo);
            if (row > 0) {
                return new Response(MessageConstants.MSG_SUCCESS, row, 0, "", request);
            } else {
                return new Response(MessageConstants.MSG_FAILED, null, 0, "", request);
            }
        }
        User user = new User();
        if (gender != null && gender != "") {
            user.setGender(gender);
        }


        if (birthday != null && birthday != "") {
            if (birthday != null) {
                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                Date date = null;
                try {
                    date = sf.parse(birthday);
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                Timestamp t1 = new Timestamp(date.getTime());
                user.setBirthday(t1);
            }

        }

        if (phone != null && phone != "") {
            if (OtherConstants.RegexpPhone(phone)) {
                UserNo userNo = userNoService.selectByPrimaryKey(userNoId);
                if (userNo != null) {
                    if (userNo.getAgent()) {
                        return new Response(MessageConstants.UNUPDATE, null, 0, "", request);
                    }
                }
                //验证码
                boolean flag = CheckCode.checkCode(phone, code, codeTime, requestHash);
                if (flag) {
                    user.setPhone(phone);
                }

            }
        }
        if (wechat != null && wechat != "") {
            user.setWechat(wechat);
        }
        user.setId(userId);
        int row1 = userService.updateByPrimaryKeySelective(user);
        if (row1 > 0) {
            return new Response(MessageConstants.MSG_SUCCESS, row1, 0, "", request);
        } else {
            return new Response(MessageConstants.MSG_FAILED, null, 0, "", request);
        }
    }

    /**
     * open ID登录
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/loginByOpenId")
    public Response loginByOpenId(HttpServletRequest request) {
        String openId = request.getParameter("openId");
        User user = null;
        UserNo userNo = new UserNo();
        JSONObject jsonObject = new JSONObject();
        if (openId != null) {
            user = userService.selectUserByOpenId(openId);
            if (user != null) {//用户存在可以进行登录

                List<UserNo> userNoList = userNoService.selectUserNoByUserId(user.getId());
                if (userNoList != null && userNoList.size() != 0) {

//                    userNo.setId(userNoList.get(0).getId());
//                    userNo.setNo(userNoList.get(0).getNo());
//                    userNo.setPwd("0000000");
                    userNo = userNoList.get(0);
                }
                String token = tokenUtils.getToken(userNo);
                jsonObject.put("token", token);
                jsonObject.put("userNo", userNo);
                return new Response(MessageConstants.MSG_SUCCESS, jsonObject, 0, "", request);

            } else {

                return new Response(MessageConstants.UNBIND_PHONE, null, 0, "", request);
            }


        } else {
            return new Response(MessageConstants.MSG_ILLEGAL_ARGUMENT, null, 0, "", request);
        }


    }


    /**
     * 微信绑定手机号
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/bindPhone", method = RequestMethod.POST)
    public Response bindPhone(HttpServletRequest request) {
        String openId = request.getParameter("openId");
        String phone = request.getParameter("phone");
        String shares = request.getParameter("share");
        String nick = request.getParameter("nick");
        String headPic = request.getParameter("headPic");
        String subscribe = request.getParameter("subscribe ");
        logger.info("微信绑定share参数------>" + shares);
        int share = 0;
        Map<String, Object> map = new HashMap<>();
        if (StringUtil.isNumeric(shares)) {
            share = Integer.parseInt(shares);
            logger.info("转换share参数------>" + share);
        }
        int userId = 0;
        if (openId != null || OtherConstants.RegexpPhone(phone)) {

            User user = userService.selectUserByOpenId(openId);

            if (user != null) {

                return new Response(MessageConstants.BIND_OPENID, null, 0, "openeId已经绑定", request);
            }

            User user2 = userService.selectUserByPhone(phone);
            if (user2 != null) {//该手机号已经存在，更新open ID
                User us = new User();
                us.setOpenId(openId);
                us.setId(user2.getId());
                us.setSubscribe(subscribe);

                int rows = userService.updateByPrimaryKeySelective(us);
                if (rows > 0) {
                    map.put("state", "1");//更新
                    return new Response(MessageConstants.MSG_SUCCESS, map, 0, "绑定成功！", request);
                } else {
                    return new Response(MessageConstants.UNBIND_OPENID, null, 0, "", request);
                }
            }
            //增加用户
            User user1 = new User();
            user1.setPhone(phone);
            user1.setOpenId(openId);
            user1.setSubscribe(subscribe);
            int row = userService.insertSelective(user1);
            if (row > 0) {
                userId = user1.getId();
                logger.info("用户userId:------>" + userId);
                //注册
                return bindRegister(request, phone, userId, share, nick, headPic, openId);

            } else {
                return new Response(MessageConstants.BIND_PHONE_FAIL, null, 0, "绑定失败！", request);
            }

        } else {
            return new Response(MessageConstants.MSG_ILLEGAL_ARGUMENT, null, 0, "参数错误！", request);
        }
    }


    /**
     * 绑定时注册账号
     *
     * @param request
     * @param phone
     * @param userId
     * @return
     */
    private Response bindRegister(HttpServletRequest request, String phone, int userId, int share, String nick, String headPic, String openId1) {
        UserNo userNo = new UserNo();
        String openId = null;
        String userName = null;
        String source = "二维码";
        logger.info("参数share----->" + share);
        try {
            userNo.setPwd(MD5Util.getEncryptedPwd("000000"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        userNo.setNo("xls" + phone);
        userNo.setUserId(userId);
        short n = 100;
        userNo.setSort(n);
        userNo.setRegisterTime(new Timestamp(System.currentTimeMillis()));
        userNo.setRankId(1);
        userNo.setShare(share);
        userNo.setNick(nick);
        userNo.setHeadPic(headPic);
        int row1 = userNoService.insertSelective(userNo);
        if (row1 > 0) {
            logger.info("绑定注册成功userNo------>" + userNo.getId());
            //注册成功，返代金券
            RestTemplate restTemplate = new RestTemplate();
            String url = HttpRequestConfig.finaceServerUrl + "/wap/Add";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            MultiValueMap<String, String> paramMap = new LinkedMultiValueMap<>();
            paramMap.add("userNoId", userNo.getId() + "");
            paramMap.add("classify", "3");
            paramMap.add("amount", finace.getVouchers() + "");
            paramMap.add("remark", userNo.getNo() + "注册赠送");

            HttpEntity<MultiValueMap<String, String>> req = new HttpEntity<>(paramMap, headers);
            ResponseEntity<String> resp = restTemplate.postForEntity(url, req, String.class);

            //注册成功，返代给推荐人金券
            logger.info("注册成功，返代给推荐人金券:----->" + share);
            MultiValueMap<String, String> paramMap1 = new LinkedMultiValueMap<>();
            paramMap1.add("userNoId", share + "");
            paramMap1.add("classify", "3");
            paramMap1.add("amount", finace.getVouchers() + "");
            paramMap1.add("remark", userNo.getNo() + "注册赠送");

            HttpEntity<MultiValueMap<String, String>> req1 = new HttpEntity<>(paramMap1, headers);
            ResponseEntity<String> resp1 = restTemplate.postForEntity(url, req1, String.class);

            //增加缓存
            redisTemplate.opsForValue().set("userNo" + userNo.getId(), userNo);
            //发送短信
            userName = userNo.getNo();
            String pwd = null;
            if (openId1 != null) {
                pwd = openId1.substring(2, 10);
            }
            String randomNumCode = Md5.getRandomNumCode(4);
            try {
                SendSmsResponse response = SmsDemo.sendSms(phone, randomNumCode);
            } catch (ClientException e) {
                e.printStackTrace();
            }
            UserNo userNo1 = null;
            //获取缓存数据
            Object object = redisTemplate.opsForValue().get("userNo" + share);
            if (object != null) {
                userNo1 = (UserNo) object;
            } else {
                userNo1 = userNoService.selectByPrimaryKey(share);
            }

            User user = null;
            if (userNo1 != null) {
                //获取缓存数据
                Object obj = redisTemplate.opsForValue().get("user" + share);
                if (obj != null) {
                    user = (User) obj;
                } else {
                    user = userService.selectByPrimaryKey(userNo1.getUserId());//分享人
                }

            }


            if (user != null) {
                openId = user.getOpenId();//分享人openID
            }

//            String res1 = SMSAPI.SMSAPI_ShareRegin(user.getPhone(), userName, source, smsConfig);//分享人
            try {
                SendSmsResponse response = SmsDemo.sendSms(phone, randomNumCode);
            } catch (ClientException e) {
                e.printStackTrace();
            }

            if (openId != null) {
                return new Response(MessageConstants.MSG_SUCCESS, openId, 0, "绑定成功！", request);
            } else {
                return new Response(MessageConstants.MSG_SUCCESS, "2", 0, "绑定成功！分享人open ID未绑定！", request);
            }

        } else {
            return new Response(MessageConstants.BIND_PHONE_FAIL, null, 0, "绑定失败！", request);
        }
    }

    /**
     * 申请店铺获取用户的相关资料
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/getUserBankInfo")
    public Response getUserBankInfo(HttpServletRequest request) {
        String userNoIds = request.getParameter("userNoId");
        int userNoId = 0;
        int userId = 0;
        if (StringUtil.isNumeric(userNoIds)) {
            userNoId = Integer.parseInt(userNoIds);
        } else {
            return new Response(MessageConstants.MSG_ILLEGAL_ARGUMENT, null, 0, "", request);
        }

        UserNo userNo = userNoService.selectByPrimaryKey(userNoId);

        if (userNo == null) {
            return new Response(MessageConstants.MSG_SUCCESS, userNo, 0, "该用户不存在！", request);
        }

        userId = userNo.getUserId();
        UserBankInfo userBankInfo = userService.selectUserBankByUserId(userId);
        return new Response(MessageConstants.MSG_SUCCESS, userBankInfo, 0, "", request);
    }

    /**
     * 修改姓名和身份证
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateNameAndCarId")
    public Response updateNameAndCarId(HttpServletRequest request) {
        String userNoIds = request.getParameter("userNoId");
        int userNoId = 0;
        int userId = 0;
        if (userNoIds != null && userNoIds != "" && StringUtil.isNumeric(userNoIds)) {
            userNoId = Integer.parseInt(userNoIds);
            UserNo userNo = userNoService.selectByPrimaryKey(userNoId);
            if (userNo != null) {
                userId = userNo.getUserId();
            }

            String name = request.getParameter("name");
            String cardId = request.getParameter("cardId");
            User user = new User();
            user.setName(name);
            user.setCardid(cardId);
            user.setId(userId);
            int row = userService.updateByPrimaryKeySelective(user);
            if (row > 0) {
                return new Response(MessageConstants.MSG_SUCCESS, row, 0, "", request);
            } else {
                return new Response(MessageConstants.MSG_SYS_ERROR, null, 0, "", request);
            }

        } else {
            return new Response(MessageConstants.MSG_ILLEGAL_ARGUMENT, null, 0, "", request);
        }

    }

    /**
     * 修改会员编号等级
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateRankId")
    public Response updateRankId(HttpServletRequest request) {
        String userNoIds = request.getParameter("userNoId");
        String rankId = request.getParameter("rankId");
        int userNoId = 0;
        int rankIdInt = 0;
        if (userNoIds != null && userNoIds != "" && StringUtil.isNumeric(userNoIds)) {
            userNoId = Integer.parseInt(userNoIds);
            rankIdInt=Integer.parseInt(rankId);
            int row = userNoService.updateRankId(rankIdInt,userNoId);
            if (row > 0) {
                return new Response(MessageConstants.MSG_SUCCESS, row, 0, "", request);
            } else {
                return new Response(MessageConstants.MSG_SYS_ERROR, null, 0, "", request);
            }
        } else {
            return new Response(MessageConstants.MSG_ILLEGAL_ARGUMENT, null, 0, "", request);
        }

    }

    /**
     * 获取用户和用户编号的信息
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/getUserAndNoInfo")
    public Response getUserAndNoInfo(HttpServletRequest request) {
        //用户编号，用户名字，用户ID
        String userNo = request.getParameter("userNo");
        if (userNo == null || userNo == "") {
            return new Response(MessageConstants.MSG_ILLEGAL_ARGUMENT, null, 0, "", request);
        }
        UserAndUserNoInfo userAndUserNoInfo = userNoService.selectUserAndUserNoByNo(userNo);

        //编号ID，用户名，
        return new Response(MessageConstants.MSG_SUCCESS, userAndUserNoInfo, 0, "", request);
    }


    /**
     * 验证支付密码是否正确
     *
     * @param map
     * @param request
     * @return
     */
    @UserLoginToken
    @ResponseBody
    @RequestMapping(value = "/checkPayPwd", method = RequestMethod.POST)
    public Response checkPayPwd(@RequestParam Map<String, Object> map, HttpServletRequest request) {
        UserNo userNo = null;
        try {
            userNo = userNoService.checkPayPwd(map, request);
            if (userNo != null) {
                return new Response(MessageConstants.MSG_SUCCESS, 1, 0, "支付密码正确!", request);
            } else {
                return new Response(MessageConstants.MSG_INVALID_LOGIN, 0, 0, "支付密码错误！", request);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Response(MessageConstants.MSG_INVALID_LOGIN, 0, 0, "运行异常！", request);
        }
    }

    /**
     * 根据用户编号ID列表查询用户信息
     *
     * @param map
     * @param request
     * @return
     */
    //@UserLoginToken
    @ResponseBody
    @RequestMapping(value = "/getOrderNoList", method = RequestMethod.GET)
    public Response getOrderNoList(@RequestParam Map<String, Object> map, HttpServletRequest request) {
        List<UserNo> list = new ArrayList<>();
        try {
            list = userNoService.selectUserNoByList(map, request);
            if (list != null && list.size() > 0) {
                return new Response(MessageConstants.MSG_SUCCESS, list, 0, "获取成功!", request);
            } else {
                return new Response(MessageConstants.MSG_INVALID_LOGIN, 0, 0, "获取失败！", request);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Response(MessageConstants.MSG_INVALID_LOGIN, 0, 0, "运行异常！", request);
        }
    }


    /**
     * 找回密码
     *
     * @param
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/findLoginPwd", method = RequestMethod.POST)
    public Response findLoginPwd(HttpServletRequest request) {
        String phone = "";
        String code = "";
        String codeTime = "";
        String requestHash = "";
        String no = null;
        String pwd = "";
        UserNo userNo1 = null;
        phone = request.getParameter("phone");
        code = request.getParameter("code");

        codeTime = request.getParameter("codeTime");
        requestHash = request.getParameter("hash");
        no = request.getParameter("userNo");
        pwd = request.getParameter("pwd");

        String encrytPwd = null;
        boolean flag = CheckCode.checkCode(phone, code, codeTime, requestHash);
        if (flag) {
            try {
                encrytPwd = MD5Util.getEncryptedPwd(pwd);
            } catch (Exception e) {
                return new Response(MessageConstants.MSG_SYS_ERROR, "0", 0, "", request);
            }


           UserNo userNo2= userNoService.getUserNoByUserNo(no);
            UserNo userNo = new UserNo();
            userNo.setPwd(encrytPwd);
            userNo.setNo(no);

           if(userNo2!=null){
               userNo.setId(userNo2.getId());
           }else{
               return new Response(MessageConstants.MSG_USER_INEXISTENCE, "0", 0, "", request);
           }

            int row = userNoService.updateByPrimaryKeySelective(userNo);

            if (row > 0) {
                return new Response(MessageConstants.MSG_SUCCESS, "1", 0, "", request);
            } else {
                return new Response(MessageConstants.MSG_SYS_ERROR, "0", 0, "", request);
            }
        } else {
            return new Response(MessageConstants.MSG_VERIFY_ERROR, "0", 0, "", request);
        }


    }


}
